<template>
  <view class="business">
    <view class="form">
      <uni-forms
        ref="valiForm"
        :rules="rules"
        :modelValue="form"
        :border="true"
      >
        <uni-forms-item
          label="问题提出人"
          required
          name="postUserName"
          label-width="110"
        >
          <uni-easyinput
            v-model="form.postUserName"
            placeholder="请输入问题提出人"
          />
        </uni-forms-item>
        <uni-forms-item label="凭证类型" name="voucherTypeId" label-width="110">
          <uni-data-select
            v-model="form.voucherTypeId"
            :localdata="voucherTypeList"
            @change="voucherTypeChange"
            placeholder="请选择凭证类型"
          ></uni-data-select>
        </uni-forms-item>
        <uni-forms-item
          label="行政区划"
          required
          name="mofDivCode"
          label-width="110"
        >
          <uni-data-picker
            placeholder="请选择行政区划"
            popup-title="请选择行政区划"
            :localdata="mofdivList"
            v-model="form.mofDivCode"
            @change="onchange"
            @nodeclick="onnodeclick"
            @popupopened="onpopupopened"
            @popupclosed="onpopupclosed"
            :map="{ text: 'label', value: 'value' }"
          >
            <template slot="default">
              <view class="processSelect">
                <view :class="['select', { selected: form.mofDivName }]">
                  {{ form.mofDivName ? form.mofDivName : '请选择行政区划' }}
                </view>
              </view>
            </template>
          </uni-data-picker>
        </uni-forms-item>
        <uni-forms-item
          label="单位名称"
          required
          name="deptId"
          label-width="110"
        >
          <uni-data-picker
            placeholder="请选择单位名称"
            popup-title="请选择单位名称"
            :localdata="deptList"
            v-model="form.deptId"
            @change="onchangeDept"
            @nodeclick="onnodeclickDept"
            @popupopened="onpopupopenedDept"
            @popupclosed="onpopupclosedDept"
            :map="{ text: 'label', value: 'id' }"
          >
            <template slot="default">
              <view class="processSelect">
                <view :class="['select', { selected: form.deptName }]">
                  {{ form.deptName ? form.deptName : '请选择单位名称' }}
                </view>
              </view>
            </template>
          </uni-data-picker>
        </uni-forms-item>
        <uni-forms-item label="操作类型" required name="type" label-width="110">
          <radio-group @change="typeChange" class="radio-group">
            <label
              class="radio-item"
              v-for="item in typeList"
              :key="item.value"
            >
              <view>
                <radio
                  :value="item.value"
                  :checked="item.value === currentType"
                />
              </view>
              <view>{{ item.text }}</view>
            </label>
          </radio-group>
        </uni-forms-item>
        <uni-forms-item label="级别" required name="levels" label-width="110">
          <radio-group @change="levelChange" class="radio-group">
            <label
              class="radio-item"
              v-for="item in levelsList"
              :key="item.value"
            >
              <view>
                <radio
                  :value="item.value"
                  :checked="item.value === currentLevel"
                />
              </view>
              <view>{{ item.text }}</view>
            </label>
          </radio-group>
        </uni-forms-item>
        <uni-forms-item label="凭证号" name="voucherNo" label-width="110">
          <view class="textBox">
            <uni-easyinput
              type="textarea"
              v-model="form.voucherNo"
              placeholder="请输入凭证号"
            />
          </view>
        </uni-forms-item>
        <uni-forms-item label="问题描述" name="content" label-width="110">
          <view class="textBox">
            <uni-easyinput
              type="textarea"
              v-model="form.content"
              placeholder="请输入问题描述"
            />
          </view>
        </uni-forms-item>
        <uni-forms-item label="图片" name="imgList" label-width="110">
          <view class="uploadBox">
            <uploadImg
              v-model="form.imgList"
              :files="form.imgList"
              :operable="true"
            ></uploadImg>
          </view>
        </uni-forms-item>
        <uni-forms-item label="文件" name="fileList" label-width="110">
          <view class="uploadBox">
            <uploadFile
              v-if="showFile"
              v-model="form.fileList"
              :alreadyFiles="form.fileList"
            >
            </uploadFile>
          </view>
        </uni-forms-item>
      </uni-forms>
    </view>

    <view class="btnBox">
      <view class="btn">
        <button class="confirm" :disabled="disabled" @click="checkUser">
          送审
        </button>
        <button class="draft" :disabled="disabled" @click="submitForm">
          保存
        </button>
        <button class="cancel" @click="cancel">取消</button>
      </view>
    </view>

    <uni-popup ref="popup" background-color="#fff">
      <view class="popup-content">
        <view class="title"><h3>送审</h3></view>
        <uni-forms
          ref="commentForm"
          :modelValue="commentForm"
          :border="true"
          class="commentForm"
        >
          <uni-forms-item label="指派人员" name="assignee" label-width="110">
            <uni-data-select
              v-model="commentForm.assignee"
              :localdata="userList"
              @change="userChange"
              placeholder="请选择指派人员"
            ></uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="送审意见" name="comment" label-width="110">
            <uni-easyinput
              type="textarea"
              v-model="commentForm.comment"
              placeholder="请输入送审意见"
            />
          </uni-forms-item>
        </uni-forms>
        <view class="btns">
          <button class="confirm" @click="submitComment">确定</button>
          <button class="cancel" @click="cancelComment">取消</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { buildTree, renameModfdiv, renameDept } from '@/utils/index.js'
import uploadFile from '@/components/upload-file/upload-file.vue'
import uploadImg from '@/components/upload-img/upload-img.vue'
export default {
  components: {
    uploadFile,
    uploadImg,
  },
  data() {
    return {
      flowKey: '',
      disabled: false,
      form: {
        id: null,
        mofDivCode: null,
        mofDivName: null,
        voucherTypeId: null,
        postUserName: null,
        deptId: null,
        deptName: null,
        type: null,
        levels: null,
        voucherNo: null,
        fileList: [],
        imgIds: [],
        imgList: [],
        fileIds: [],
      },
      showFile: false,
      rules: {
        postUserName: {
          rules: [
            {
              required: true,
              errorMessage: '请输入问题提出人',
            },
          ],
        },
        mofDivCode: {
          rules: [
            {
              required: true,
              errorMessage: '请选择行政区划',
            },
          ],
        },
        deptId: {
          rules: [
            {
              required: true,
              errorMessage: '请选择单位名称',
            },
          ],
        },
        type: {
          rules: [
            {
              required: true,
              errorMessage: '请选择操作类型',
            },
          ],
        },
        levels: {
          rules: [
            {
              required: true,
              errorMessage: '请选择级别',
            },
          ],
        },
      },
      voucherTypeList: [],
      codeDisabled: false,
      mofdivList: [],
      codeData: {}, //暂存行政区划的数据
      deptList: [],
      deptData: {}, //暂存单位名称的数据
      typeList: [],
      levelsList: [],
      currentType: null,
      currentLevel: null,
      commentForm: {
        assignee: null,
        comment: null,
      },
      userList: [],
      saveTaskId: null,
    }
  },
  async onLoad(query) {
    if (query?.taskId) {
      this.saveTaskId = query.taskId
    }
    if (query?.flowKey) {
      this.flowKey = query.flowKey
    }
    if (query?.id) {
      await this.$u.api.getBusinessOrder(query.id).then((res) => {
        if (res.code == '200') {
          this.form = res.data
          this.currentType = res.data.type
          this.currentLevel = res.data.levels
          if (typeof this.form.voucherTypeId === 'number') {
            this.form.voucherTypeId = res.data.voucherTypeId.toString()
          }
          this.form.imgList = res.data.imgList.map((item) => {
            return {
              ...item,
              url: this.vuex_config.baseUrl + item.fileUrl,
            }
          })
          this.form.fileList = res.data.fileList.map((item) => {
            return {
              ...item,
              originalFilename: item.fileName,
              url: this.vuex_config.baseUrl + item.fileUrl,
            }
          })
          this.form.content = res.data.content ? res.data.content.replace(/<[^>]*>/g, '') : ''
          this.showFile = true //编辑状态下，获取到数据之后再展示上传文件组件
        }
      })
    } else {
      this.showFile = true //新增状态下，显示文件上传组件
      let userInfo = uni.getStorageSync('sgkj_userInfo')
      this.form.postUserName = userInfo.nickName
    }
    this.$u.api.voucherTypeList().then((res) => {
      if (res.code == '200') {
        this.voucherTypeList = res.data.map((item) => {
          return {
            text: item.code,
            value: item.code,
          }
        })
      }
    })
    this.$u.api.mofdivList().then((res) => {
      if (res.code == '200') {
        const treeData = buildTree(res.data)
        this.mofdivList = renameModfdiv(treeData)
      }
    })
    this.$u.api.deptTree().then((res) => {
      if (res.code == '200') {
        this.deptList = res.data
      }
    })
    this.$u.api.getDicts('order_level').then((res) => {
      if (res.code == '200') {
        this.levelsList = res.data.map((item) => {
          return {
            text: item.dictLabel,
            value: item.dictValue,
          }
        })
      }
    })
    this.$u.api.getDicts('order_type').then((res) => {
      if (res.code == '200') {
        this.typeList = res.data.map((item) => {
          return {
            text: item.dictLabel,
            value: item.dictValue,
          }
        })
      }
    })
  },
  methods: {
    voucherTypeChange(val) {
      // console.log(val, '??')
    },
    userChange(val) {
      // console.log(val, '??')
    },
    onchange(e) {
      // console.log(e, 'onchange')
    },
    onpopupopened(e) {
      // console.log(e, 'onpopupopened')
    },
    onpopupclosed(e) {
      // console.log(e, 'onpopupclosed')
      //处理不同步
      this.$nextTick(() => {
        this.form.mofDivCode = this.codeData.value
        this.form.mofDivName = this.codeData.label
        if (!this.codeData) return
      })
      // console.log(this.form, 'popupclosed')
    },
    onnodeclick(e) {
      //级联选择器点击后
      this.$u.api.deptTree({ mofDivCode: this.codeData.value }).then((res) => {
        if (res.code == '200') {
          this.deptList = renameDept(res.data)
        }
      })
      this.codeData = e
      // console.log(e, 'onnodeclick')
    },
    onchangeDept(e) {
      // console.log(e, 'onchange')
    },
    onpopupopenedDept(e) {
      // console.log(e, 'onpopupopened')
    },
    onpopupclosedDept(e) {
      // console.log(e, 'onpopupclosed')
      //处理不同步
      this.$nextTick(() => {
        this.form.deptId = this.deptData.value
        this.form.deptName = this.deptData.label
        if (!this.deptData) return
      })
      // console.log(this.form, 'popupclosed')
    },
    onnodeclickDept(e) {
      //级联选择器点击后
      this.deptData = e
      // console.log(e, 'onnodeclick')
    },
    typeChange(val) {
      // console.log(val, 'typeChange')
      for (let i = 0; i < this.typeList.length; i++) {
        if (this.typeList[i].value === val.detail.value) {
          this.currentType = i
          this.form.type = val.detail.value
          break
        }
      }
    },
    levelChange(val) {
      // console.log(val, 'typeChange')
      for (let i = 0; i < this.levelsList.length; i++) {
        if (this.levelsList[i].value === val.detail.value) {
          this.currentLevel = i
          this.form.levels = val.detail.value
          break
        }
      }
    },
    cancel() {
      uni.navigateBack()
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.valiForm
        .validate()
        .then(() => {
          if (this.form.id != null) {
            this.disabled = true //防止重复提交//同时校验
            // console.log(this.form, 'form')
            this.form.imgIds = this.form.imgList.map(
              (item) => item.id || item.fileId
            )
            this.form.fileIds = this.form.fileList.map(
              (item) => item.id || item.fileId
            )
            this.$u.api
              .updateBusinessOrder({ ...this.form, submitStatus: 0 })
              .then((res) => {
                if (res.code == '200') {
                  this.$u.toast('修改成功')
                  this.cancel()
                }
              })
            this.disabled = false
          } else {
            this.disabled = true //防止重复提交//同时校验
            // console.log(this.form, 'form')
            this.form.imgIds = this.form.imgList.map((item) => item.fileId)
            this.form.fileIds = this.form.fileList.map((item) => item.fileId)
            this.$u.api
              .addBusinessOrder({
                ...this.form,
                submitStatus: 0,
                flowKey: this.flowKey,
              })
              .then((res) => {
                if (res.code == '200') {
                  this.$u.toast('新增成功')
                  this.cancel()
                }
              })
            this.disabled = false
          }
        })
        .catch((err) => {
          console.log('校验不通过', err)
        })
    },
    // 新增编辑页面送审
    checkUser() {
      this.$refs.valiForm.validate().then(() => {
        if (this.form.id != null) {
          this.disabled = true //防止重复提交//同时校验
          this.form.imgIds = this.form.imgList.map(
            (item) => item.id || item.fileId
          )
          this.form.fileIds = this.form.fileList.map(
            (item) => item.id || item.fileId
          )
          this.$u.api
            .updateBusinessOrder({ ...this.form, submitStatus: 0 })
            .then((res) => {
              if (res.code == '200') {
                this.$u.api
                  .nextFlowNode({ taskId: this.saveTaskId })
                  .then((response) => {
                    if (response.code == '200') {
                      this.userList = response.data.userList.map((item) => {
                        return {
                          text: item.nickName,
                          value: item.userId,
                        }
                      })
                      this.$refs.popup.open('center')
                    } else {
                      this.$u.toast(response.msg)
                    }
                    this.disabled = false
                  })
              }
            })
        } else {
          this.disabled = true //防止重复提交//同时校验
          this.form.imgIds = this.form.imgList.map((item) => item.fileId)
          this.form.fileIds = this.form.fileList.map((item) => item.fileId)
          this.$u.api
            .addBusinessOrder({
              ...this.form,
              submitStatus: 0,
              flowKey: this.flowKey,
            })
            .then((response) => {
              this.saveTaskId = response.data.taskId
              this.$u.api
                .nextFlowNode({ taskId: response.data.taskId })
                .then((res) => {
                  if (res.code == '200') {
                    this.userList = res.data.userList.map((item) => {
                      return {
                        text: item.nickName,
                        value: item.userId,
                      }
                    })
                    this.$refs.popup.open('center')
                  }
                })
            })
          this.disabled = false
        }
      })
    },
    // 提交送审
    submitComment() {
      this.$u.api
        .completeBusinessOrder({
          taskId: this.saveTaskId,
          assignee: this.commentForm.assignee,
          comment: this.commentForm.comment,
        })
        .then((res) => {
          if (res.code == '200') {
            this.$refs.popup.close()
            this.cancel()
            this.$u.toast('送审成功')
          }
        })
    },
    cancelComment() {
      this.commentForm.assignee = ''
      this.commentForm.comment = ''
      this.$refs.popup.close()
    },
  },
}
</script>

<style lang="scss" scoped>
/deep/ .uni-input-placeholder {
  font-size: 14px;
  color: #6a6a6a !important;
}

/deep/ .is-disabled {
  //修改禁用的是输入框背景
  background-color: #f5f7fa !important;
}

/deep/ .uni-select--disabled {
  //下拉框禁用下文字颜色
  .uni-select__input-text {
    color: #d5d5d5;
  }
}

/deep/ .uni-data-tree {
  .uni-data-tree-input {
    .input-value {
      .selected-area {
        .uni-scroll-view {
          width: 300rpx !important;
        }
      }
    }
  }
}

/deep/ .uni-forms-item__label {
  //label宽度
  width: 110px;
}

/deep/ .is-input-error-border {
  //文本框校验时 边框颜色和占位符不变红色
  border-color: #dcdfe6 !important;

  .uni-easyinput__placeholder-class {
    color: #6a6a6a;
  }
}

/deep/ .uni-easyinput__placeholder-class {
  color: #6a6a6a;
}

/deep/ .uni-numbox {
  margin-top: 5px;
}

/deep/ .uni-forms-item--border {
  padding: 10px 16px; //表单item左右间距
}

.business {
  .form {
    font-size: 28rpx;
    width: 100%;
    padding: 10rpx 0rpx 80rpx;

    .processSelect {
      display: flex;
      align-items: center;
      font-size: 12px;
      height: 35px;
      padding-left: 10px;
      width: 100%;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      color: #6a6a6a;

      .selected {
        font-size: 14px;
        color: #333333;
      }
    }

    .textBox {
      position: relative;

      .wordLimit {
        position: absolute;
        bottom: 5rpx;
        right: 10rpx;
        font-size: 10px;
        color: #6a6a6a;
      }
    }

    .radio-group {
      display: flex;

      .radio-item {
        display: flex;
        margin-right: 10rpx;
      }
    }
  }

  .btnBox {
    z-index: 0;
    width: 100%;
    // position: fixed;
    // bottom: 0;
    background-color: #fff;
    height: 160rpx;
    padding: 0 34rpx;

    // z-index: 999;
    .btn {
      width: 100%;
      height: 160rpx;
      padding: 36rpx 0 0;
      display: flex;
      justify-content: space-between;

      .confirm,
      .cancel,
      .draft {
        width: 200rpx;
        height: 72rpx;
        text-align: center;
        line-height: 72rpx;
        border-radius: 8rpx;
        font-size: 32rpx;
      }

      .confirm {
        color: #ffffff;
        background: #007aff;
      }

      .cancel,
      .draft {
        color: #007aff;
        background-color: #ffffff;
        border: 2rpx solid #007aff;
      }
    }
  }

  .popup-content {
    min-height: 500rpx;
    min-width: 450rpx;
    .title {
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
    }
    .commentForm {
      margin: 20rpx 0;
    }
    .btns {
      margin: 30rpx 0;
      display: flex;
      justify-content: space-around;
      .confirm,
      .cancel {
        width: 160rpx;
        height: 60rpx;
        text-align: center;
        line-height: 60rpx;
        border-radius: 8rpx;
        font-size: 32rpx;
      }

      .confirm {
        color: #ffffff;
        background: #007aff;
      }

      .cancel {
        color: #007aff;
        background-color: #ffffff;
        border: 2rpx solid #007aff;
      }
    }
  }
}
</style>
